package com.xixing.weixin.utils;

import com.xixing.weixin.response.ArticleItem;
import org.apache.http.Consts;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;
import org.htmlparser.Node;
import org.htmlparser.NodeFilter;
import org.htmlparser.Parser;
import org.htmlparser.filters.*;
import org.htmlparser.tags.LinkTag;
import org.htmlparser.util.NodeList;
import org.htmlparser.util.ParserException;

import java.io.IOException;
import java.security.KeyManagementException;
import java.security.NoSuchAlgorithmException;
import java.text.MessageFormat;
import java.util.*;

/**
 * Created with IntelliJ IDEA.
 * User: Kay
 * Date: 13-4-9
 * Time: 下午3:44
 * To change this template use File | Settings | File Templates.
 */
public class GzhuLibraryUtils {
    public static final String loginUrl = "http://lib.gzhu.edu.cn/opac/LoginSystem1.aspx";
    public static final String bookUrl = "http://lib.gzhu.edu.cn/opac/BookRetr.aspx?page=1&Index=4&KeyWord={0}&LocLmt=%28%E6%89%80%E6%9C%89%E5%9C%B0%E7%82%B9%29&SrchTab=0&Acurate=0";
    public static final String bookLinkUrl = "http://lib.gzhu.edu.cn/opac/";
    public static final String PRESS_REGEX = "&nbsp;&nbsp;&nbsp;&nbsp;";

    private static Map<String, DefaultHttpClient> userHttpClients = new HashMap<String, DefaultHttpClient>();

    private static HttpClient createHttpSSLClient(String username) throws NoSuchAlgorithmException, KeyManagementException {

        DefaultHttpClient httpClient = userHttpClients.get(username);
        if (httpClient != null) {
            return httpClient;
        }

        httpClient = HttpClientUtils.createHttpsClient();
        userHttpClients.put(username, httpClient);
        return httpClient;
    }

    public static boolean login(String username, String password) {
        try {
            DefaultHttpClient httpClient = (DefaultHttpClient) createHttpSSLClient(username);

            HttpGet httpGet = new HttpGet(loginUrl);
            httpClient.execute(httpGet);
            httpGet.releaseConnection();
            //获取附加码
            String loginHtml = HttpClientUtils.get(httpClient, loginUrl);
            Parser parser = Parser.createParser(loginHtml, "GB2312");
            NodeList nodes = parser.extractAllNodesThatMatch(new AndFilter(new NodeFilter[]{
                    new TagNameFilter("span"),
                    new HasAttributeFilter("id", "labAppendix"),
                    new HasAttributeFilter("style", "display:inline-block;")
            }));
            String checkCode = nodes.elementAt(0).toPlainTextString();


            // 登陆.
            List<NameValuePair> nvps = new ArrayList<NameValuePair>();
            nvps.add(new BasicNameValuePair("UserName", username));
            nvps.add(new BasicNameValuePair("Password", password));
            nvps.add(new BasicNameValuePair("txtAppendix", checkCode));
            nvps.add(new BasicNameValuePair("btnLogin", "登录"));
            nvps.add(new BasicNameValuePair("__VIEWSTATE", HtmlParseUtils.findLibViewState(loginHtml)));
            nvps.add(new BasicNameValuePair("__EVENTVALIDATION", HtmlParseUtils.findLibEventValition(loginHtml)));
            String html = HttpClientUtils.post(httpClient, loginUrl, nvps);
            String redirectUrl = "http://lib.gzhu.edu.cn/opac/RdrLoanRetr.aspx";
            html = HttpClientUtils.get(httpClient, redirectUrl);
            System.out.println(html);
            return !html.contains("【网上图书馆】登录");


        } catch (Exception e) {
            return false;
        }

    }

    private static String findResponse(HttpResponse scoreResponse) throws IOException {
        HttpEntity entity = scoreResponse.getEntity();
        String result = EntityUtils.toString(entity);
        EntityUtils.consume(entity);
        return result;
    }

    public static String findBook(String bookName) throws IOException {
        DefaultHttpClient httpClient = HttpClientUtils.createHttpsClient();
        String url = MessageFormat.format(bookUrl, bookName);
        return HttpClientUtils.get(httpClient, url);
    }

    public static List<ArticleItem> parseBook(String html) throws ParserException {
        List<String> bookNames = new ArrayList<String>();
        List<String> bookUrls = new ArrayList<String>();
        List<String> pressNames = new ArrayList<String>();
        List<ArticleItem> articles = new ArrayList<ArticleItem>();
        //取书名
        Parser parser = Parser.createParser(html, "GB2312");
        NodeList nodes = parser.extractAllNodesThatMatch(new AndFilter(new NodeFilter[]{
                new TagNameFilter("a"),
                new HasParentFilter(new TagNameFilter("td")),
                new HasSiblingFilter(new TagNameFilter("font"))
        }));

        //取出版社
        //<td height=20 bgcolor="#ffffff" valign=bottom>
        Parser parser2 = Parser.createParser(html, "GB2312");
        NodeList nodes2 = parser2.extractAllNodesThatMatch(new AndFilter(new NodeFilter[]{
                new HasAttributeFilter("height", "20"),
                new HasAttributeFilter("bgcolor", "#ffffff"),
                new HasAttributeFilter("valign", "bottom"),
                new TagNameFilter("td")
        }));

        //解析书名和url
        if (nodes != null) {
            for (int i = 0; i < nodes.size(); i++) {
                Node node = nodes.elementAt(i);
                String text = node.toPlainTextString();
                String link = bookLinkUrl + ((LinkTag) node).getLink();
                bookNames.add(text);
                bookUrls.add(link);
            }
        }

        //解析出版社
        if (nodes2 != null) {
            for (int i = 0; i < nodes2.size(); i++) {
                Node node = nodes2.elementAt(i);
                String text = node.toPlainTextString();

                int startIndex = text.indexOf(PRESS_REGEX) + PRESS_REGEX.length();
                int endIndex = text.indexOf(PRESS_REGEX, startIndex);
                String substring = text.substring(startIndex, endIndex);
                pressNames.add(substring);
            }
        }

        //书的数目
        int arSize = bookNames.size() >= 5 ? 5 : bookNames.size();
        for (int size = 0; size < arSize; size++) {
            ArticleItem article = new ArticleItem();
            article.setPicUrl(ResourceBundle.getBundle("command").getString("BookExecutor.url"));
            article.setTitle(bookNames.get(size));
            article.setUrl(bookUrls.get(size));
            article.setDescription(pressNames.get(size));
            articles.add(article);
        }

        return articles;
    }

}
